﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LinkCard.Model;

namespace LinkCard.Dao
{
    public class ImageDao:ITopLinkDao
    {
        public int Add(object obj)
        {
            var rs = 0;
            try
            {
                var db = new TopLinkEntities();
                var objAdd = (Image)obj;
                db.AddToImages(objAdd);
                rs = db.SaveChanges();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return rs;
        }

        public int Update(object obj)
        {
            var rs = 0;
            try
            {
                var db = new TopLinkEntities();
                var objUpdate = (Image)obj;
                var id = objUpdate.ImageID;
                var oldObj = db.Images.FirstOrDefault(t => t.ImageID == id);
                if (oldObj != null)
                {
                    oldObj.Link = objUpdate.Link;
                    oldObj.DateLog = objUpdate.DateLog;
                    oldObj.Description = objUpdate.Description;
                    oldObj.AlbumID = objUpdate.AlbumID;
                    rs = db.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return rs;
        }

        public int Delete(object obj)
        {
            var rs = 0;
            try
            {
                var db = new TopLinkEntities();
                var objDel = (Image)obj;
                var id = objDel.ImageID;
                var oldObj = db.Images.FirstOrDefault(t => t.ImageID == id);
                if (oldObj != null)
                {
                    db.DeleteObject(oldObj);
                    rs = db.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return rs;
        }

        public Image GetById(long id)
        {
            var ct = new Image();
            try
            {
                var db = new TopLinkEntities();
                ct = db.Images.FirstOrDefault(t => t.ImageID == id);
            }
            catch (Exception)
            {
                throw;
            }
            return ct;
        }

        public List<Image> GetAll()
        {
            var lst = new List<Image>();
            try
            {
                var db = new TopLinkEntities();
                lst = db.Images.ToList();
            }
            catch (Exception)
            {
                throw;
            }
            return lst;
        }
    }
}
